﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace SharedUtils
{
    // From http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/
    public class Camera2d
    {
        protected float _zoom; // Camera Zoom
        protected float _rotation; // Camera Rotation ignore for now
        public Matrix _transform; // Matrix Transform
        public Vector2 _pos; // Camera Position
        public String name { get; set; } // Name

        public Camera2d()
        {
            _zoom = 1.0f;
            _pos = Vector2.Zero;
        }

        public Camera2d(String name) : this()
        {
            this.name = name;
        }

        // Sets and gets zoom
        public float Zoom
        {
            get { return _zoom; }
            set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image
        }

        // Camera Rotation 
        public float Rotation
        {
            get { return _rotation; }
            set { _rotation = value; }
        }

        // Auxiliary function to move the camera
        public void Move(Vector2 amount)
        {
            _pos += amount;
        }
        // Get set position
        public Vector2 Pos
        {
            get { return _pos; }
            set { _pos = value; }
        }

        public Matrix get_transformation(GraphicsDevice graphicsDevice, float ViewportWidth, float ViewportHeight)
        {
            //_transform = (Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
            //    Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)));

            
            // Originally
            _transform =       // Thanks to o KB o for this solution
                Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) 
                * Matrix.CreateRotationZ(Rotation) 
                * Matrix.CreateScale(new Vector3(Zoom, Zoom, 1))
                //* Matrix.CreateTranslation(new Vector3(0, 0, 0))
                //* Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0))
                ;
            return _transform;
        }

        public Camera2d copy()
        {
            Camera2d c = new Camera2d();
            c._pos = _pos;
            c._rotation = _rotation;
            c._transform = _transform;
            c._zoom = _zoom;
            return c;
        }
    }
}
